/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.notice.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.notice.entity.NoticeInfo;
import vip.xiaonuo.biz.modular.notice.entity.NoticeOrg;
import vip.xiaonuo.biz.modular.notice.enums.NoticeOrgStatusEnum;
import vip.xiaonuo.biz.modular.notice.enums.NoticeStatusEnum;
import vip.xiaonuo.biz.modular.notice.mapper.NoticeInfoMapper;
import vip.xiaonuo.biz.modular.notice.mapper.NoticeOrgMapper;
import vip.xiaonuo.biz.modular.notice.param.*;
import vip.xiaonuo.biz.modular.notice.service.NoticeInfoService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 通知表Service接口实现类
 *
 * @author h
 * @date  2024/10/24 15:09
 **/
@Service
public class NoticeInfoServiceImpl extends ServiceImpl<NoticeInfoMapper, NoticeInfo> implements NoticeInfoService {
    @Resource
    private NoticeOrgMapper noticeOrgMapper;

    @Override
    public Page<NoticeInfo> page(NoticeInfoPageParam noticeInfoPageParam) {
        QueryWrapper<NoticeInfo> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(noticeInfoPageParam.getTitle())) {
            queryWrapper.lambda().like(NoticeInfo::getTitle, noticeInfoPageParam.getTitle());
        }
        if(ObjectUtil.isNotEmpty(noticeInfoPageParam.getType())) {
            queryWrapper.lambda().eq(NoticeInfo::getType, noticeInfoPageParam.getType());
        }
        if(ObjectUtil.isNotEmpty(noticeInfoPageParam.getStartPublicTime()) && ObjectUtil.isNotEmpty(noticeInfoPageParam.getEndPublicTime())) {
            queryWrapper.lambda().between(NoticeInfo::getPublicTime, noticeInfoPageParam.getStartPublicTime(), noticeInfoPageParam.getEndPublicTime());
        }
        if(ObjectUtil.isNotEmpty(noticeInfoPageParam.getStatus())) {
            queryWrapper.lambda().eq(NoticeInfo::getStatus, noticeInfoPageParam.getStatus());
        }
        if(!StpUtil.hasRoleOr("bizAdmin","browser_role")){
            // 查询本单位信息
            SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
            queryWrapper.lambda().in(NoticeInfo::getId,this.listNoticeByOrgId(loginUser.getOrgId()));
        }

        if(ObjectUtil.isAllNotEmpty(noticeInfoPageParam.getSortField(), noticeInfoPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(noticeInfoPageParam.getSortOrder());
            queryWrapper.orderBy(true, noticeInfoPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(noticeInfoPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(NoticeInfo::getId);
        }

        Page<NoticeInfo> noticeInfoPage = this.baseMapper.selectPage(CommonPageRequest.defaultPage(), queryWrapper);
        for(NoticeInfo noticeInfo : noticeInfoPage.getRecords()){
            noticeInfo.setUserIds(this.listNoticeOrgId(noticeInfo.getId()));
        }
        return noticeInfoPage;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(NoticeInfoAddParam noticeInfoAddParam) {
        NoticeInfo noticeInfo = BeanUtil.toBean(noticeInfoAddParam, NoticeInfo.class);
        if(ObjectUtil.equal(NoticeStatusEnum.PUB.getValue(),noticeInfoAddParam.getStatus())){
            SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
            noticeInfo.setPublicUserId(loginUser.getId());
            noticeInfo.setPublicUserName(loginUser.getName());
            noticeInfo.setPublicOrgId(loginUser.getOrgId());
            noticeInfo.setPublicOrgName(loginUser.getOrgName());
            noticeInfo.setPublicTime(DateUtil.date());
        }
        this.save(noticeInfo);
        if(noticeInfoAddParam.getType()==1){
            // 添加组织机构
            for(String orgId : noticeInfoAddParam.getOrgIds()){
                NoticeOrg noticeOrg = new NoticeOrg();
                noticeOrg.setOrgId(orgId);
                noticeOrg.setStatus(NoticeStatusEnum.INI.getValue());
                noticeOrg.setNoticeId(noticeInfo.getId());
                noticeOrgMapper.insert(noticeOrg);
            }
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(NoticeInfoEditParam noticeInfoEditParam) {
        NoticeInfo noticeInfo = this.queryEntity(noticeInfoEditParam.getId());
        BeanUtil.copyProperties(noticeInfoEditParam, noticeInfo);
        if(ObjectUtil.equal(NoticeStatusEnum.PUB.getValue(),noticeInfoEditParam.getStatus())){
            SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
            noticeInfo.setPublicUserId(loginUser.getId());
            noticeInfo.setPublicUserName(loginUser.getName());
            noticeInfo.setPublicOrgId(loginUser.getOrgId());
            noticeInfo.setPublicOrgName(loginUser.getOrgName());
            noticeInfo.setPublicTime(DateUtil.date());
        }
        this.updateById(noticeInfo);
        if(noticeInfoEditParam.getType()==1){
            // 删除全部已读未读信息
            this.noticeOrgMapper.deleteByNoticeId(noticeInfo.getId());
            // 重新添加已读未读人员
            for(String orgId : noticeInfoEditParam.getOrgIds()){
                NoticeOrg noticeOrg = new NoticeOrg();
                noticeOrg.setOrgId(orgId);
                noticeOrg.setStatus(NoticeOrgStatusEnum.INI.getValue());
                noticeOrg.setNoticeId(noticeInfo.getId());
                noticeOrgMapper.insert(noticeOrg);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<NoticeInfoIdParam> noticeInfoIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(noticeInfoIdParamList, NoticeInfoIdParam::getId));
        for(NoticeInfoIdParam noticeInfoIdParam : noticeInfoIdParamList){
            // 删除全部已读未读信息
            this.noticeOrgMapper.deleteByNoticeId(noticeInfoIdParam.getId());
        }
    }

    @Override
    public NoticeInfo detail(NoticeInfoIdParam noticeInfoIdParam) {
        SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
        //修改已读信息
        LambdaUpdateWrapper<NoticeOrg> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(NoticeOrg::getUserId,loginUser.getId());
        updateWrapper.set(NoticeOrg::getStatus,NoticeOrgStatusEnum.READ.getValue());
        updateWrapper.set(NoticeOrg::getReadTime, DateUtil.date());
        updateWrapper.eq(NoticeOrg::getNoticeId,noticeInfoIdParam.getId());
        updateWrapper.eq(NoticeOrg::getOrgId,loginUser.getOrgId());
        this.noticeOrgMapper.update(null,updateWrapper);
        return this.queryEntity(noticeInfoIdParam.getId());
    }

    @Override
    public NoticeInfo queryEntity(String id) {
        NoticeInfo noticeInfo = this.getById(id);
        if(ObjectUtil.isEmpty(noticeInfo)) {
            throw new CommonException("通知表不存在，id值为：{}", id);
        }
        return noticeInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updStatus(NoticeInfoStatusParam noticeInfoStatusParam) {
        NoticeInfo noticeInfo = this.queryEntity(noticeInfoStatusParam.getId());
        // 重新发布时修改已读消息为未读
        if(ObjectUtil.equal(NoticeStatusEnum.PUB.getValue(),noticeInfoStatusParam.getStatus())){
            SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
            noticeInfo.setPublicUserId(loginUser.getId());
            noticeInfo.setPublicUserName(loginUser.getName());
            noticeInfo.setPublicOrgId(loginUser.getOrgId());
            noticeInfo.setPublicOrgName(loginUser.getOrgName());
            noticeInfo.setPublicTime(DateUtil.date());
            this.noticeOrgMapper.updateStatus(NoticeOrgStatusEnum.INI.getValue(),noticeInfo.getId());
        }
        noticeInfo.setStatus(noticeInfoStatusParam.getStatus());
        this.updateById(noticeInfo);
    }

    /**
     * 根据通知公告ID查询通知公告人员ID
     * @param noticeId
     * @return
     */
    private String[] listNoticeOrgId(String noticeId){
        List<NoticeOrg> orgList = this.listNoticeOrg(noticeId);
        List<String> orgIdList = orgList.stream().map(NoticeOrg::getOrgId).collect(Collectors.toList());
        return ArrayUtil.toArray(orgIdList,String.class);
    }

    /**
     * 根据通知公告ID查询通知公告人员信息
     * @param noticeId
     * @return
     */
    private List<NoticeOrg> listNoticeOrg(String noticeId){
        LambdaQueryWrapper<NoticeOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NoticeOrg::getNoticeId,noticeId);
        List<NoticeOrg> noticeOrgList = this.noticeOrgMapper.selectList(queryWrapper);
        return noticeOrgList;
    }

    /**
     * 根据通知公告ID查询通知公告人员ID
     * @param orgId
     * @return
     */
    private String[] listNoticeByOrgId(String orgId){
        LambdaQueryWrapper<NoticeOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NoticeOrg::getOrgId,orgId);
        List<NoticeOrg> noticeOrgList = this.noticeOrgMapper.selectList(queryWrapper);
        List<String> noticeIdList = noticeOrgList.stream().map(NoticeOrg::getNoticeId).collect(Collectors.toList());
        if(ObjectUtil.isEmpty(noticeIdList)){
            return new String[]{orgId};
        }
        return ArrayUtil.toArray(noticeIdList,String.class);
    }
}
